package com.hymjweb.demo.hymj.system_maintenance.user_role.service;

import com.github.pagehelper.PageInfo;
import com.hymjweb.demo.framework.result.BaseResultMap;
import com.hymjweb.demo.framework.result.MIniUIGridResultMap;
import com.hymjweb.demo.framework.sys.BaseService;
import com.hymjweb.demo.framework.sys.SysConstant;
import com.hymjweb.demo.framework.util.DataTypeUtil;
import com.hymjweb.demo.hymj.system_maintenance.role.bean.RolePojo;
import com.hymjweb.demo.hymj.system_maintenance.role.service.RoleService;
import com.hymjweb.demo.hymj.system_maintenance.user.bean.XtUserPojo;
import com.hymjweb.demo.hymj.system_maintenance.user.service.XtUserService;
import com.hymjweb.demo.hymj.system_maintenance.user_role.bean.UserRolePojo;
import com.hymjweb.demo.hymj.system_maintenance.user_role.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserRoleService extends BaseService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleService roleService;

    @Autowired
    private XtUserService xtUserService;

    public Object queryUserListByRoleId(Map param) {
        // 分页初始化
        this.pageListInit(param);
        List<Map<String, Object>> list = userRoleMapper.queryUserListByRoleId(param);
        PageInfo pageInfo = new PageInfo(list);
        MIniUIGridResultMap resultMap = new MIniUIGridResultMap(pageInfo);
        return resultMap;
    }

    public Object queryUnselectedRoleUser(Map param) {
        // 分页初始化
        this.pageListInit(param);
        List<Map<String, Object>> list = userRoleMapper.queryUnselectedRoleUser(param);
        PageInfo pageInfo = new PageInfo(list);
        MIniUIGridResultMap resultMap = new MIniUIGridResultMap(pageInfo);
        return resultMap;
    }

    public Object querySelectedRoleUser(Map param) {
        // 分页初始化
        this.pageListInit(param);
        List<Map<String, Object>> list = userRoleMapper.querySelectedRoleUser(param);
        PageInfo pageInfo = new PageInfo(list);
        MIniUIGridResultMap resultMap = new MIniUIGridResultMap(pageInfo);
        return resultMap;
    }

    public List<UserRolePojo> queryUserRoleByUserId(String userId) {
        if (userId != null && !userId.isEmpty()) {
            return userRoleMapper.queryUserRoleByUserId(userId);
        }
        return null;
    }

    /**
     * 保存角色用户
     *
     * @param param
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public Object saveRoleUser(Map param) throws Exception {
        if (param == null || param.isEmpty()) {
            throwException("保存用户角色参数错误!");
        }

        BaseResultMap baseResultMap = new BaseResultMap();
        baseResultMap.setOk(true);
        baseResultMap.setMessage("角色用户保存成功!");

        // {roleId:roleIdValue,roleUserIds:roleUserIdsArray}
        // 获取角色 ID
        String roleId = DataTypeUtil.toStringObject(param.get("roleId"));
        if(DataTypeUtil.isEmptyStr(roleId)){
            throwException("保存用户角色,角色ID丢失!");
        }

        RolePojo rolePojo = roleService.getRolePojoById(roleId);

        List<String> roleUserIds = (List<String>) param.get("roleUserIds");

        if (roleUserIds == null || roleUserIds.isEmpty()) {
            throwException("保存角色用户时用户丢失!");
        }

        List<UserRolePojo> userRolePojoList = new ArrayList<>();
        // 构建构用户角色对象
        for (String userId : roleUserIds) {
            UserRolePojo userRolePojo = new UserRolePojo();
            userRolePojo.setRoleId(roleId);
            userRolePojo.setUserId(userId);
            // 检测是否有重复,userId 与 roleId 构建成 UK
            UserRolePojo dbUserRolePojo = checkUnique(userRolePojo);
            if (dbUserRolePojo != null) {
                XtUserPojo xtUserPojo = xtUserService.findObjectById(dbUserRolePojo.getUserId());
                baseResultMap.setOk(false);
                baseResultMap.setMessage("添加用户【" + xtUserPojo.getName() + "】在【" + rolePojo.getName() + "】中已存在，不能重复添加!");
                return baseResultMap;
            }
            // 设置 ID，这个步骤很关键
            userRolePojo.setId(this.getSysStrId());
            // 加入到待插入列表
            userRolePojoList.add(userRolePojo);
        }

        int affectRows = userRoleMapper.batchInsertUserRole(userRolePojoList);

        if (affectRows <= SysConstant.INT_ZERO) {
            baseResultMap.setOk(false);
            baseResultMap.setMessage("向指定角色中增加用户失败，请重试!");
            return baseResultMap;
        }
        return baseResultMap;
    }

    private UserRolePojo checkUnique(UserRolePojo userRolePojo) {
        return userRoleMapper.checkUnique(userRolePojo);
    }


    /**
     * 根据角色id与用户 id 删除对应用户的角色
     *
     * @param param
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public Object deleteRoleUser(Map<String, Object> param) throws Exception {
        if(param==null || param.isEmpty()){
            throwException("用户角色删除参数错误!");
        }
        // {roleId:roleIdValue,roleUserIds:deleteUserIdsValue}
        BaseResultMap baseResultMap = new BaseResultMap();
        baseResultMap.setOk(true);
        baseResultMap.setMessage("角色用户删除成功!");

        String roleId = DataTypeUtil.toStringObject(param.get("roleId"));
        if (DataTypeUtil.isEmptyStr(roleId)) {
            throwException("删除角色用户时角色ID丢失");
        }
        List<String> roleUserIds = (List<String>) param.get("roleUserIds");
        if (roleUserIds == null || roleUserIds.isEmpty()) {
            baseResultMap.setOk(false);
            baseResultMap.setMessage("删除角色用户时用户丢失!");
            return baseResultMap;
        }
        int affectRows = SysConstant.INT_ZERO;
        for (String roleUserId : roleUserIds) {
            int affectRow = userRoleMapper.deleteByRoleIdAndUserId(roleId, roleUserId);
            affectRows += affectRow;
        }

        if (affectRows <= SysConstant.INT_ZERO) {
            baseResultMap.setOk(false);
            baseResultMap.setMessage("删除角色用户失败!");
        }

        return baseResultMap;
    }

}
